package cn.com.dstz.admin.action;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.common.web.springmvc.RealPathResolver;
import cn.com.dstz.upload.Upload;
import cn.com.dstz.utils.Common;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.DateUtils;
import cn.com.dstz.utils.FillNameQuery;
import cn.com.dstz.utils.UploadUtils;
import cn.com.dstz.utils.ValidUtils;

/**
 * 皮肤管理Action
 * 1. 提供皮肤LOGO的上传
 * 2. 提供皮肤文件的上传
 * 3. 上传并没有提供真正的格式验证,只是单纯的判断后缀
 * @author 叶装装
 * 
*
 */
public class SkinAct extends BaseAction{
	
	public void list( ){
		
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		String sql = "select * from dstz_skin ";
		this.responseToJsonObject( this.paginationBySQL( sql, null, valueMap,  "datetime" )  );
		return;
	}
	
	/**
	 * 添加皮肤, 并不进行logo的保存
	 */
	public void add( ){
		int validSaveOrUpdate = validSaveOrUpdate( 0 );
		Map< String, Object > jsonMap = new HashMap< String, Object >( );
		
		if( validSaveOrUpdate > 0 ){
			jsonMap.put( "success", 1 );
			jsonMap.put( "msg", validSaveOrUpdate );
			
			this.responseToJsonObject( jsonMap );
			return;
		}
		
		int returnId = baseService.save( "dstz_skin", DataBaseUtils.getData( new String[]{
				"name",  "dir", "datetime", "logo"
		}, new Object[]{
				name, dir, DateUtils.getCurrentTime( ),  ""
		} ), true );
		
		// 如果添加成功，则创建目录
		if( returnId > 0 ){
			String realPath = realPathResolver.get( skin );
			File directory = new File( realPath + File.separator + dir );
			UploadUtils.checkDirAndCreate( directory );	// 验证目录是否存在，不存在就创建
		}
		
		jsonMap.put( "success", returnId > 0 ? 0 : 1  );
		jsonMap.put( "msg", returnId );
		
		this.addLog( returnId, "skin", 0,  name );
		
		this.responseToJsonObject( jsonMap );
		
		return;
		
	}
	
	/**
	 * 编辑皮肤
	 * 编辑皮肤的时候，如果改变dir,需要将dir进行重命名(要考虑到文件是否被使用，锁定情况，所以，皮肤不能修改目录)
	 */
	public void edit( ){
		int validSaveOrUpdate = validSaveOrUpdate( 1 );
		Map< String, Object > jsonMap = new HashMap< String, Object >( );
		
		if( validSaveOrUpdate > 0 ){
			jsonMap.put( "success", 1 );
			jsonMap.put( "msg", validSaveOrUpdate );
			
			this.responseToJsonObject( jsonMap );
			return;
		}
		
		int update = baseService.update( "dstz_skin", DataBaseUtils.getData( new String[]{
				"name"
		}, new Object[]{
				name
		} ), DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		jsonMap.put( "success", update > 0 ? 0 : 1  );
		jsonMap.put( "msg", update );
		
		this.addLog( update, "skin", 1,  name );
		
		this.responseToJsonObject( jsonMap );
		
	}
	
	/**
	 * 转到上传页面
	 * 当添加成功的时候，会传递添加成功的ID过来
	 * 然后从数据库中获取ID
	 */
	public String toupload( ){
		
		Map< String, Object > data = getSkinById( );	// 获取皮肤
		
		if( data == null ){
			return this.uploadresult;
		}
		
		getRequest( ).setAttribute( "data", data );	// 设置皮肤到request
		
		return this.uploadresult;
	}
	
	public String toadd( ){
		return "add";
	}
	
	public String toedit( ){
		Map< String, Object > data = getSkinById( );	// 获取皮肤
		
		if( data == null ){
			return "edit";
		}
		getRequest( ).setAttribute( "data", data );	
		return "edit";
	}
	
	/**
	 * 只有单个删除，没有批量删除
	 */
	public void delete( ){
		
		if( id == null || id == 0 ){
			this.ajaxResponse( 1 );
			return;
		}
		
		Map< String, Object > data = getSkinById( );
		
		if( data == null || data.isEmpty( ) ){
			this.ajaxResponse( 1 );
			return;
		}
		
		String dir = Common.convert( data.get( "dir" ) );	// 取得目录
		String logo = Common.convert( data.get( "logo" ) );
		
		int del = baseService.deleteBySql( "dstz_skin", DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		// 删除资源文件
		if( del > 0 ){
			
			try{
				String skinDirectory =  realPathResolver.get( skin ) + File.separator + dir;
				FileUtils.cleanDirectory( new File( skinDirectory ) );	// 删除整个目录
				
				// 删除LOGO文件
				String logoFile = realPathResolver.get( "/" ) + logo;
				String [ ] logos = new String[ ] {
						logoFile, logoFile + ".thumb.jpg"
				};
				cn.com.dstz.utils.FileUtils.deleteFile( logos, null );
				
				// 删除数据库文件
				baseService.deleteBySql( "dstz_skin_field", DataBaseUtils.getData( new String[]{
						"skinid"
				}, new Object[]{
						id
				} )  );
				this.addLog( del, "skin", 2,  id );
			}catch( IOException e ){
				e.printStackTrace();
			}
		}
		
		return;
	}
	
	
	
	/**
	 * 文件上传，没有判断大小，主要靠前端来判断
	 */
	public void logoupload( ){
		HttpServletResponse response = ServletActionContext.getResponse( );
		
		Map< String, Object > data = getSkinById( );	// 获取皮肤
		
		if( data == null ){
			this.ajaxResponse( "!无法获取皮肤数据" );
			return;
		}
		
		Upload upload = new  Upload( response,  data, realPathResolver, logo, Filedata, Filename, baseService, id);
		this.ajaxResponse( upload.doLogoUpload( ) );
		
		return;
		
	}
	
	/**
	 * 文件上传, 包括图片和txt文件，如果是txt文件将不进行图片的缩放
	 * 上传中并不处理firefox 浏览器的问题;session问题
	 */
	public void fileupload( ){
		HttpServletResponse response = ServletActionContext.getResponse( );
		Map< String, Object > data = getSkinById( );	// 获取皮肤
		
		if( data == null ){
			this.ajaxResponse( "!无法获取皮肤数据" );
			return;
		}
		
		Upload upload = new  Upload( response,  data, realPathResolver, skin, Filedata, Filename, baseService, id);
		this.ajaxResponse( upload.doFileUpload( ) );
		return;
	}
	
	private Map< String, Object> getSkinById( ){
		if( id == null || id == 0 ){
			alertMsg( null );
			return null;
		}
		String sql = " select * from dstz_skin where id=:id";
		Map< String, Object > data = baseService.queryForMap( sql, FillNameQuery.fillValue( sql, id ) );
		
		if( data == null || data.isEmpty( ) ){
			alertMsg( null );
			return null;
		}
		
		return data;
	}
	
	private int validSaveOrUpdate( int saveOrUpdate ){
		
		if( ValidUtils.validLength( name, 1, 32 )){
			return 1;
		}
		
		if( saveOrUpdate == 0 ){
			if( ValidUtils.validLength( dir, 1, 100 )){
				return 2;
			}
		}
		
		if( saveOrUpdate == 0 ){
			String sql = "select count(*) as a from dstz_skin where ";
			String nameSql = sql + " name=:name ";
			int dbCheck = dbCheck( nameSql, FillNameQuery.fillValue( nameSql, name ) );

			if( dbCheck > 0 ){
				return 3;
			}
			
			String dirSql = sql + " dir=:dir";
			dbCheck = dbCheck( dirSql, FillNameQuery.fillValue( dirSql, dir ));
			
			if( dbCheck > 0 ){
				return 4;
			}
		}else{
			if(! StringUtils.equals( name, oldname )){
				String sql = "select count(*) as a from dstz_skin where name=:name";
				int dbCheck = dbCheck( sql, FillNameQuery.fillValue( sql, name ) );
				
				if( dbCheck > 0 ){
					return 3;
				}
			}
			
			
			
		}
		
		return 0;
		
	}
	
	private int dbCheck( String sql, Map< String, Object > valueMap ){
		return baseService.countBySQL( sql,  valueMap );
	}
	
	
	
	//----------------------------------------------------------------------------------------------------------------------------------
	
	private static final long serialVersionUID = 1L;

	private RealPathResolver realPathResolver;		// 真实路径辅助类
	private String logo;										// logo存放目录
	private String skin;											// 皮肤存放目录
	
	private String name;							// 皮肤的名称
	private String dir;								//目录, 不以/开始
	
	private String oldname;
	
	private File  Filedata;						// 上传域
    private String Filename;				// 上传的文件名称
    
    private Integer id;
    
    private String uploadresult;					// 转到上传页面
    
	public void setRealPathResolver( RealPathResolver realPathResolver ) {
		this.realPathResolver = realPathResolver;
	}

	public void setLogo( String logo ) {
		this.logo = logo;
	}

	public void setSkin( String skin ) {
		this.skin = skin;
	}

	public String getName( ) {
		return name;
	}

	public void setName( String name ) {
		if( StringUtils.isNotBlank( name ) ){
			name = decode( name );
		}
		this.name = name;
	}

	public String getDir( ) {
		return dir;
	}

	public void setDir( String dir ) {
		if( StringUtils.isNotBlank( dir ) ){
			dir = decode( dir ); 
		}
		this.dir = dir;
	}

	public File getFiledata( ) {
		return Filedata;
	}

	public void setFiledata( File filedata ) {
		Filedata = filedata;
	}

	public String getFilename( ) {
		return Filename;
	}

	public void setFilename( String filename ) {
		Filename = filename;
	}

	public String getOldname( ) {
		return oldname;
	}

	public void setOldname( String oldname ) {
		if( StringUtils.isNotBlank( oldname ) ){
			oldname = decode( oldname ); 
		}
		this.oldname = oldname;
	}

	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		this.id = id;
	}

	public String getUploadresult( ) {
		return uploadresult;
	}

	public void setUploadresult( String uploadresult ) {
		this.uploadresult = uploadresult;
	}
	
}
